<?php

//获取网站设置信息
function Site($field) {
    $o = M('options');
    $data = $o->getField($field);
    return $data;
}


/**
  +----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
  +----------------------------------------------------------
 * @static
 * @access public
  +----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
  +----------------------------------------------------------
 * @return string
  +----------------------------------------------------------
 */
function mysubstr($str, $start = 0, $len = 20, $charset = "utf-8", $suffix = true) {
    if (function_exists("mb_substr")) {
        if ($suffix && (strlen($str) > $len)) {
            return mb_substr($str, $start, $len, $charset) . "...";
        } else {
            return mb_substr($str, $start, $len, $charset);
        }
    } elseif (function_exists('iconv_substr')) {
        if ($suffix && (strlen($str) > $len)) {
            return iconv_substr($str, $start, $len, $charset) . "...";
        } else {
            return iconv_substr($str, $start, $len, $charset);
        }
    }
}

/*
  函数说明:计算$string在$array(需为数组)中重复出现的次数.
 */

function get_array_repeats(array $array, $string) {
    $count = array_count_values($array);
    return $count[$string];
}

/**
  +----------------------------------------------------------
 * 分页封装
  +----------------------------------------------------------
 * @access  public
  +----------------------------------------------------------
 * @param   int     $count      数据条数
 *           int     $num        每页数量
 *           array   $map        当前查询条件
  +----------------------------------------------------------
 * @return  array
  +----------------------------------------------------------
 */
function pages($count, $num, $map) {

    import("@.ORG.Page");
    $p = new Page($count, $num);
    $page['firstRow'] = $p->firstRow;
    $page['listRows'] = $p->listRows;
    foreach ($map as $key => $val) {
        $p->parameter .="$key=" . urlencode($val) . "&";
    }
    $page['page'] = $p->show();
    return $page;
}



/**
 *
 * 上传图片方法
 * @param string $imagePath 图片的路径
 */
function uploadFile($h = "250", $w = "250",$path=null, $allowExts = "jpg,gif,png,jpeg") {
    $allowExts = explode(',', $allowExts);

    import("@.ORG.UploadFile");
    $upload = new UploadFile(); // 实例化上传类
    $upload->saveRule = 'uniqid';
    $upload->thumbPrefix = "";
    $upload->uploadReplace = true; //如果图片相同，覆盖相同图片
    $upload->maxSize = -1; // 设置附件上传大小
    //$upload->allowExts = $allowExts; // 设置附件上传类型
    $path =empty($path)? "Uploads/" . date("Ymd") . "/" : $path;
    if (!is_dir($path)){
        mkdir($path);
    }
    $upload->savePath = $path; // 设置附件上传目录
    //生成缩略图
    $upload->thumb = true;
    $upload->autoSub = false;
    $upload->thumbPath = $path; //要保存的路径
    $upload->thumbMaxHeight = $h; //图片高度
    $upload->thumbMaxWidth = $w; //图片宽度
    $upload->thumbPrefix = "m_"; //默认前缀为空

    if (!$upload->upload()) { // 上传错误 提示错误信息
        return($upload->getErrorMsg());
    } else {
        // 上传成功 获取上传文件信息
        $info = $upload->getUploadFileInfo();
        return $info;
    }
}

function auto_charset($fContents, $from = 'gbk ', $to = 'utf-8') {
    $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
    $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
    if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
//如果编码相同或者非字符串标量则不转换
        return $fContents;
    }
    if (is_string($fContents)) {
        if (function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($fContents, $to, $from);
        } elseif (function_exists('iconv')) {
            return iconv($from, $to, $fContents);
        } else {
            return $fContents;
        }
    } elseif (is_array($fContents)) {
        foreach ($fContents as $key => $val) {
            $_key = auto_charset($key, $from, $to);
            $fContents[$_key] = auto_charset($val, $from, $to);
            if ($key != $_key)
                unset($fContents[$key]);
        }
        return $fContents;
    }
    else {
        return $fContents;
    }



}


function pushMsgByIos($msg,$token,$type){
    if(empty($token)||strlen($token)!=64){
        log::write($msg."推送失败");
        exit;
    }
    // 这里是我们上面得到的deviceToken，直接复制过来（记得去掉空格）
    //$deviceToken = '53c87033977131849bbb8483e801bd798ca57e4a0e21502b59be41998f097983';
    $deviceToken=$token;
    // Put your private key's passphrase here:
    $passphrase = '12!@as';

    // Put your alert message here:
    $message = $msg;

    ////////////////////////////////////////////////////////////////////////////////

    $ctx = stream_context_create();
    if($type==1){
    	stream_context_set_option($ctx, 'ssl', 'local_cert', 'Public/pem/hxyz_develop.pem');
    }elseif($type==2){
    	stream_context_set_option($ctx, 'ssl', 'local_cert', 'Public/pem/hxdj_develop.pem');
    }
    
    stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

    // Open a connection to the APNS server
    //这个为正是的发布地址
     //$fp = stream_socket_client(“ssl://gateway.push.apple.com:2195“, $err, $errstr, 60, //STREAM_CLIENT_CONNECT, $ctx);
    //这个是沙盒测试地址，发布到appstore后记得修改哦
    $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err,$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

    if (!$fp)
        log::write("推送信息:"."Failed to connect: $err $errstr" . PHP_EOL);
    echo 
        log::write("推送信息:"."Connected to APNS" . PHP_EOL);

    // Create the payload body
    $body['aps'] = array(
        'alert' => $message,
        'sound' => 'default'
    );

    // Encode the payload as JSON
    $payload = json_encode($body);

    // Build the binary notification
    $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

    // Send it to the server
    $result = fwrite($fp, $msg, strlen($msg));

    if (!$result)
        log::write("推送信息:"."Message not delivered" . PHP_EOL);
    else
        log::write("推送信息:"."Message successfully delivered" . PHP_EOL);

    fclose($fp);

}

?>
